<template>
  <div id="dialogPubLongVideo">
    <el-dialog
      class="about-set"
      title="添加长视频"
      :visible.sync="dialogData.isShow"
      width="600px"
      :before-close="labelHandleClose"
    >
      <div class="form-box">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-form-item label="选择学院" prop="collegeId">
            <el-select
              v-model="ruleForm.collegeId"
              filterable
              placeholder="选择学院"
            >
              <el-option
                v-for="item in collegeList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <showTagSelect
            channel="LONG_VIDEO"
            @getTagIds="getTagIds"
          ></showTagSelect>
          <el-form-item label="选择马甲" prop="userId">
            <el-select
              v-model="ruleForm.userId"
              filterable
              placeholder="请选择马甲"
              :disabled="ruleForm.canRobotRandom === true"
            >
              <el-option
                v-for="item in vestList"
                :key="item.robotId"
                :label="item.robotName"
                :value="item.robotId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="随机马甲">
            <el-switch
              v-model="ruleForm.canRobotRandom"
              :active-value="true"
              :inactive-value="false"
              active-color="#1DC8A4"
              @change="changeRandom(ruleForm.canRobotRandom)"
            ></el-switch>
          </el-form-item>
          <el-form-item label="视频标题" prop="title">
            <el-input
              class="vid-title"
              v-model="ruleForm.title"
              :maxlength="dialogData.titleLength"
              show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="视频内容" prop="content">
            <el-input
              v-model="ruleForm.content"
              type="textarea"
              :maxlength="dialogData.contentLength"
              show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="添加视频" prop="videoId">
            <el-button id="upload" type="warning">
              上传视频
            </el-button>
            <el-button @click="setCover" type="primary" :disabled="cannotEdit"
              >获取封面</el-button
            >
          </el-form-item>
          <el-form-item class="min-margin" label="添加封面" prop="cover">
            <uploadSingImg
              v-loading="upImgLoading"
              class="upImg"
              ref="uploadSImg"
              :imgUrl="ruleForm.cover"
              accept=".jpg,.png"
              :maxSize="10"
              :showDeleteIcon="true"
              :uploadPolyv="uploadPolyvData"
              :WHScale="[1.5, 1.9, '16：9']"
              @getImgUrl="getImgUrl"
            >
              <template v-slot:imgInfo
                >只能上传.jpg，.png文件，且文件不超过10M，比例限制16：9</template
              >
            </uploadSingImg>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelLabel">取 消</el-button>
        <el-button
          type="success"
          :loading="loading"
          @click="confirmLabel('ruleForm')"
          >确认</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import showTagSelect from '@common/showTagSelect' // 显性标签下拉选择公共组件
import uploadSingImg from '@common/uploadSingImg' // 上传单个图片公共组件
import { pubVideo } from '@/api/longVidManagement' // 接口
import { getPolyvcover } from '@/api/common/img' // 接口
import { getVideoPara } from '@utils/pubFunction'
import { uploadVideo } from '@utils/uploadVideo'
import {
  sysNormalDisable,
  getVestList,
  getWorkListActivities,
  getRandomRobotId
} from '@utils/dictionariesFunc'
export default {
  name: 'dialogPubLongVideo',
  msg: '长视频管理-我的发布---发布视频',
  components: {
    showTagSelect,
    uploadSingImg
  },
  props: ['dialogData'],
  data() {
    return {
      loading: false,
      upImgLoading: false,
      cannotEdit: true,
      collegeList: [], // 学院
      vestList: [{ robotId: '', robotName: '- 请选择马甲 -' }], // 选择马甲
      ruleForm: {
        cover: '', //封面图
        collegeId: '', // 学院
        userId: '', // 马甲id
        canRobotRandom: true, //是否为随机马甲，为true的话系统后端默认随机一个马甲
        title: '', // 标题
        content: '', // 视频内容
        videoId: '', // 视频vid
        sourceType: 'WH' //标题，非必传
      },
      rules: {
        collegeId: { required: true, message: 'content' },
        // userId: { required: true, message: '请选择马甲' },
        userId: {},
        title: {
          required: true,
          message: '视频标题不能为空',
          trigger: 'change'
        },
        content: {},
        videoId: { required: true, message: '请上传视频' }
      },
      polivNum: {
        polyvUserId: '',
        polyvSecretKey: '',
        polyvWriteToken: '',
        polyvReadToken: ''
      },
      upVideo: null,
      labelItems: [],
      uploadPolyvData: {
        isPolyv: true,
        vid: ''
      }
    }
  },
  computed: {
    dapengUserId() {
      return this.$store.state.user.dapengUserId
    }
  },
  watch: {
    'ruleForm.canRobotRandom': {
      // 监听随机马甲
      handler(newValue, oldValue) {
        if (newValue === true) {
          // 随机马甲启用
          this.rules.userId = {}
        } else {
          // 随机马甲关闭
          this.rules.userId = { required: true, message: '请选择马甲' }
        }
      },
      deep: true
    }
  },
  mounted() {
    this.getStatusList()
    this.getPolivNum()
  },
  methods: {
    /* 获取系统配置-保利威视 */
    getPolivNum() {
      let _this = this
      getVideoPara().then((data) => {
        this.polivNum = { ...data }
        uploadVideo(_this.polivNum, _this.saveVideo).then((resObj) => {
          _this.upVideo = resObj
        })
      })
    },
    /* 获取数据状态 */
    async getStatusList() {
      // 学院
      this.collegeList = await sysNormalDisable('sys_college')
      this.ruleForm.collegeId = this.collegeList[0].dictValue
      // 马甲
      let data1 = await getVestList(this.dapengUserId)
      this.vestList = this.vestList.concat(data1)
    },
    /* 保存上传视频 */
    saveVideo(fileData) {
      this.ruleForm.videoId = fileData.vid
      this.uploadPolyvData.vid = fileData.vid
      this.$refs.uploadSImg.deleteImg()
      this.upImgLoading = true
      this.getCoverRequire(this.ruleForm.videoId)
    },
    /*状态复位*/
    statusRest() {
      this.upImgLoading = false
      this.cannotEdit = false
    },
    /* 获取封面图 */
    setCover() {
      this.upImgLoading = true
      this.cannotEdit = true
      this.getCoverRequire(this.ruleForm.videoId)
    },
    /*封面图接口请求*/
    getCoverRequire(vid) {
      getPolyvcover(
        { vid },
        (res) => {
          if (res.startsWith('http')) {
            let time = new Date().getTime()
            let url = res + '?' + time
            this.getImgUrl(url)
            this.statusRest()
          } else {
            this.$message.warning('获取封面图失败')
            this.statusRest()
          }
        },
        (res) => {
          this.statusRest()
          this.$message.warning(res.message)
        }
      )
    },
    labelHandleClose(done) {
      this.cancelLabel()
      done()
    },
    cancelLabel() {
      // 关闭前清空
      this.loading = false
      this.upVideo.update({
        uploadSuccess: ''
      })
      clearInterval(this.upVideo.timer)
      this.upVideo.destroy()
      this.dialogData.isShow = false
    },
    /* 改变随机马甲按钮状态 */
    changeRandom(status) {
      if (status === true) {
        // 启用随机马甲
        if (this.vestList.length === 0) {
          this.$message({
            message: '马甲列表为空，无法选择随机马甲',
            type: 'error'
          })
          this.ruleForm.canRobotRandom = true
        }
      }
    },
    /*整合选择的标签*/
    setIabelInfos() {
      let ary = []
      this.labelItems.forEach((item, index) => {
        let { labelProperty: labelCategoryProperty, labelId, labelName } = item
        let obj = {
          labelCategoryProperty,
          labelId,
          labelName
        }
        ary.push(obj)
      })
      return [...ary]
    },
    /* 确认提交 */
    async confirmLabel(formName) {
      this.loading = true
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let obj = { ...this.ruleForm }
          // userId,随机马甲时，取随机马甲，否则取当前马甲的robotId
          if (this.ruleForm.canRobotRandom === true) {
            obj.userId = (await getRandomRobotId(this.dapengUserId)) || ''
          }
          //选中标签
          obj.labelInfos = this.setIabelInfos()
          pubVideo(
            obj,
            (response) => {
              this.loading = false
              this.$emit('refresh')
              this.cancelLabel()
            },
            (response) => {
              this.loading = false
              this.$message.warning('发布视频失败，' + response.message)
            }
          )
        } else {
          this.loading = false
          return false
        }
      })
    },
    /* 获取选中的显性标签 */
    getTagIds(items) {
      this.labelItems = [...items]
    },
    //封面图设置
    getImgUrl(url) {
      this.$set(this.ruleForm, 'cover', url)
    }
  }
}
</script>

<style lang="less">
#dialogPubLongVideo {
  @import url('~@common/style/textarea.less');
  .vid-title {
    .el-input__inner {
      padding-right: 45px;
    }
  }
  .upImg {
    width: 180px;
  }
  .test-img {
    width: 180px;
    height: 180px;
  }
}
</style>
